//
//  CustomTextView.swift
//  Qianzoo
//
//  Created by franze on 2017/5/24.
//  Copyright © 2017年 franze. All rights reserved.
//

import UIKit

class CustomTextView: UITextView {
    private var _placeholder:String!
    private var _placeholderColor:UIColor!
    
    var placeholder:String!{
        set{
            _placeholder = newValue
            setNeedsDisplay()
        }
        get{
            return _placeholder
        }
    }
    
    var placeholderColor:UIColor{
        set{
            _placeholderColor = newValue
            setNeedsDisplay()
        }
        get{
            return _placeholderColor
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        textContainerInset = UIEdgeInsetsMake(18, 5, 18, 5)
        font = UIFont.systemFont(ofSize: 16)
        layer.borderWidth = 1
        layer.borderColor = UIColor.gray.cgColor
        layer.cornerRadius = 20
        layer.masksToBounds = true
        
        _placeholderColor = UIColor.gray
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: .UITextViewTextDidChange, object: self)
    }


    @objc func textDidChange(){
        let paragraph = NSMutableParagraphStyle()
        paragraph.lineSpacing = 10
        attributedText = NSAttributedString(string: text, attributes: [NSAttributedStringKey.paragraphStyle : paragraph,NSAttributedStringKey.font:font!])
        setNeedsDisplay()
    }
    
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        if self.hasText{
            return
        }
        let paragraph = NSMutableParagraphStyle()
        paragraph.lineSpacing = 10
        let Rect = CGRect(x: 10, y: 20, width: bounds.width-20, height: CGFloat.greatestFiniteMagnitude)
        if placeholder != nil{
            placeholder.draw(in: Rect, withAttributes: [NSAttributedStringKey.foregroundColor:_placeholderColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14),NSAttributedStringKey.paragraphStyle:paragraph])
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
